﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using DeepEarth.Toolkit.Common;

namespace DeepEarth.Toolkit.Controls
{
	[TemplatePart(Name = PART_modesSelector, Type = typeof(Selector))]
	public sealed class MapModeSelector : MapInteractionControl
	{
		private const string PART_modesSelector = "PART_modesSelector";

		private Selector _modeSelector;

		public MapModeSelector()
		{
			DefaultStyleKey = typeof(MapModeSelector);
		}

		public override void OnApplyTemplate()
		{
			base.OnApplyTemplate();
			_modeSelector = (Selector)GetTemplateChild(PART_modesSelector);
			if (_modeSelector != null)
				_modeSelector.DisplayMemberPath = "Name";
		}
		
		protected override void ViewChanged(Map.Core.MapView newView, Map.Core.MapView oldView)
		{
			if (_modeSelector == null) return;
		
			_modeSelector.ClearValue(ItemsControl.ItemsSourceProperty);
			_modeSelector.ClearValue(Selector.SelectedItemProperty);

			if (newView != null)
			{
				_modeSelector.Visibility = Visibility.Visible;

				_modeSelector.SetBinding(ItemsControl.ItemsSourceProperty,
				                         new Binding("Mode.AvailableNonOverlayModes") {Source = newView});
				_modeSelector.SetBinding(Selector.SelectedItemProperty,
				                         new Binding("Mode.Mode") {Source = newView, Mode = BindingMode.TwoWay});
			} else
			{
				_modeSelector.Visibility = Visibility.Collapsed;
			}
		}
	}
}
